﻿using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace Limiting.MiddleWares
{
    public class LimitingMiddleWare
    {
        private readonly RequestDelegate _next;
        private readonly ILimiting _limiting;
        private readonly LimitingOptions _options;

        public LimitingMiddleWare(
            RequestDelegate next,
            ILimiting limiting,
            LimitingOptions options)
        {
            _next = next;
            _limiting = limiting;
            _options = options;
        }

        public async Task Invoke(HttpContext context)
        {
            //调用设置限流键的委托
            var identity = _options.IdentityDelegate.Invoke(context);
            //检查建是否被限流
            var result = await _limiting.CheckIdentityLimited(identity);
            if (result)
            {
                //如果用户被限流调用限流的回调委托
                _options.CallbackDelegate.Invoke(context);
            }
            else
            {
                //否则下一步
                await _next.Invoke(context);
            }
        }
    }
}
